package com.mengdie.shuidi.ui.activity;

import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;

import com.blankj.utilcode.utils.FileUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.mengdie.shuidi.AppManager;
import com.mengdie.shuidi.event.RobustEvent;
import com.mengdie.shuidi.helper.UIHelper;
import com.mengdie.shuidi.manager.MDAccountMgr;
import com.mengdie.shuidi.manager.RobustVersionManager;
import com.mengdie.shuidi.model.AppEntity;
import com.mengdie.shuidi.utils.AESHelper;
import com.mengdie.shuidi.widgets.LoadingDialog;
import com.orhanobut.logger.Logger;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by apple on 16/10/17.
 */

public class BaseActivity extends AppCompatActivity {
    public LoadingDialog loginLoadingDialog;


    public AppEntity appConfig;
    //  private NetReceiver mReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        AppManager.getAppManager().addActivity(this);
        PushAgent.getInstance(this).onAppStart();

        //  mReceiver = new NetReceiver();
    }

    @Override
    protected void onStart() {
        super.onStart();
        // register();
    }

//    private void register() {
//        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
//        registerReceiver(mReceiver,filter);
//    }

    /**
     * 创建Dialog对象
     *
     * @param msg
     * @param isblack
     */
    public void createLoginLoadDialog(String msg, boolean isblack) {
        loginLoadingDialog = new LoadingDialog(this, msg, isblack);
        loginLoadingDialog.show();
    }


    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        AppManager.getAppManager().removeActivity(this);
        loginLoadingDialog = null;
        // unregisterReceiver(mReceiver);

    }

    /**
     * 接收推送消息----->需要热更新
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void ongetRobustMsg(RobustEvent event) {
        int vCode = event.getData().getvCode();
        String vName = event.getData().getvName();
        String downLoadUrl = event.getData().getAndroidUrl();
        Logger.e("baseactivity");
        //本地虚拟版本小于后台传来的虚拟版本,需要更新
        if (RobustVersionManager.getInstance().getvCode() < vCode) {
            goGetPatch(vCode, vName, downLoadUrl);
        }
    }

    /**
     * 网络请求patch.jar
     *
     * @param vCode
     * @param vName
     * @param downLoadUrl
     */
    private void goGetPatch(final int vCode, final String vName, final String downLoadUrl) {
        OkGo.get(downLoadUrl)
                .execute(new FileCallback(Environment.getExternalStorageDirectory().getPath() + File.separator + "robust", "patch.jar") {
                    @Override
                    public void onSuccess(File file, Call call, Response response) {
                        loadPatch(vCode, vName, downLoadUrl);
                    }
                });

    }

    //加载补丁
    private void loadPatch(final int vCode, final String vName, final String downLoadUrl) {
        //解密
        AESHelper.decryptFile("abcdefghabcdefgh", Environment.getExternalStorageDirectory().getPath() + File.separator + "robust/patch.jar"
                ,Environment.getExternalStorageDirectory().getPath() + File.separator + "robust1/patch.jar");
        //解密之后清除掉 robust 文件夹
        FileUtils.deleteDir(Environment.getExternalStorageDirectory().getPath() + File.separator + "robust");

        //移动
        FileUtils.copyFile(Environment.getExternalStorageDirectory().getPath() + File.separator + "robust1/patch.jar",
                Environment.getExternalStorageDirectory().getPath() + File.separator + "robust/patch.jar");
        //删除
        FileUtils.deleteDir(Environment.getExternalStorageDirectory().getPath() + File.separator + "robust1");

        UIHelper.loadPatch(true, vCode, vName);
    }


    /**
     * 关闭Dialog对象
     */
    public void stopLoginDialog() {
        if (loginLoadingDialog != null) {
            loginLoadingDialog.close();
        }
    }


    public boolean isPwdLenght(String pass) {
        if (pass.length() >= 6 && pass.length() <= 20) {
            return true;
        } else {
            return false;
        }
    }

    public boolean isPhoneLenght(String phone) {
        if (phone.length() == 11) {
            return true;
        } else {
            return false;
        }
    }


    public String mapSession() {
        HashMap<String, String> map = new HashMap<>();
        map.put("session_id", MDAccountMgr.getInstance().getSessionId());
        JSONObject json = new JSONObject(map);
        return json.toString();
    }

    public String mapVerifyId(String time) {
        HashMap<String, String> map = new HashMap<>();
        map.put("verify_id", time);
        JSONObject json = new JSONObject(map);
        return json.toString();
    }

}
